package com.tarena.lbs.content.dao.repository.impl;


import com.github.pagehelper.PageInfo;
import com.tarena.lbs.content.dao.repository.CategoryRepository;
import com.tarena.lbs.content.pojo.po.ArticleCategoryPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
@Slf4j
public class CategoryRepositoryImpl implements CategoryRepository {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public PageInfo<ArticleCategoryPO> pageList() {

        // 构建查询所有分类的查询条件
        NativeQuery nativeQuery = NativeQuery.builder()
                .withPageable(PageRequest.of(0, 100)) // 默认查询前100条记录
                //.withQuery(q -> q.match(m -> m.field("categoryName").query(categoryName))) // 匹配分类名称
                .build();
        // 执行ES查询
        SearchHits<ArticleCategoryPO> searchHits = elasticsearchTemplate.search(nativeQuery, ArticleCategoryPO.class);

        // 转换结果
        List<ArticleCategoryPO> categoryList = searchHits.get().map(hit -> hit.getContent()).collect(Collectors.toList());

        // 构建PageInfo对象
        PageInfo<ArticleCategoryPO> pageInfo = new PageInfo<>();
        pageInfo.setList(categoryList);
        pageInfo.setPageNum(1);
        pageInfo.setPageSize(100);
        pageInfo.setTotal(searchHits.getTotalHits());
        pageInfo.setPages((int) Math.ceil((double) searchHits.getTotalHits() / 100));

        return pageInfo;
    }
}
